package com.example.zjx8969.myapplication.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.example.zjx8969.myapplication.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class IosLoadingView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr), LifecycleObserver {
    private val mainScope = MainScope()
    private var job: Job? = null

    //#a5a5a5,#b7b7b7,#c0c0c0,#c9c9c9,#d2d2d2,#dbdbdb,#e4e4e4,#e4e4e4
    val colors = arrayOf(
            ContextCompat.getColor(context, R.color.a5),
            ContextCompat.getColor(context, R.color.b7),
            ContextCompat.getColor(context, R.color.c0),
            ContextCompat.getColor(context, R.color.c9),
            ContextCompat.getColor(context, R.color.d2),
            ContextCompat.getColor(context, R.color.db),
            ContextCompat.getColor(context, R.color.e4),
            ContextCompat.getColor(context, R.color.e4)
    )
    val paint = Paint().also {
        it.isAntiAlias = true
        it.style = Paint.Style.FILL
        it.strokeWidth = 4f
    }
    private var halfX = 0
    private var halfY = 0
    private var currentColorIndex = 0
//        get() = (++field) and 7

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            it.translate(halfX.toFloat(), halfY.toFloat())

            for (id in 0..7) {
                val index = (currentColorIndex + id) and 7
                paint.color = colors[index]
                it.save()
                it.rotate(45f * id)
                it.drawLine(10f, 0f, halfX.toFloat(), 0f, paint)
                it.restore()
            }
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        halfX = w shr 1
        halfY = h shr 1
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun startAnimation() {
        if (job?.isActive == true) return
        job = mainScope.launch {
            while (true) {
                delay(100)
                currentColorIndex = ++currentColorIndex and 7
                invalidate()
            }
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopAnimation() {
        job?.cancel()
    }
}